package org.example.springboot3.controller;

import jakarta.annotation.Resource;
import org.example.springboot3.service.FileStorageService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/images")
public class FileUploadController {
    @Resource
    private FileStorageService fileStorageService;

    // 上传文件
    @PostMapping("/upload")
    public ResponseEntity<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(Collections.singletonMap("error", "文件为空"));
            }
            String fileName = fileStorageService.storeFile(file);
            return ResponseEntity.ok()
                    .body(Collections.singletonMap("url",fileName)); // 直接访问路径
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", "上传失败：" + e.getMessage()));
        }
    }

    @DeleteMapping("/delete/{fileName}")
    public String deleteFile(@PathVariable String fileName) {
        // 校验文件名合法性（禁止路径穿越）
        if (fileName.contains("..")) {
            return "非法文件名";
        }
        boolean success = fileStorageService.deleteFile(fileName);
        return success ? "删除成功" : "删除失败";
    }
}